package de.tum.icuproject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import de.tum.icuproject.MainActivity.SectionsPagerAdapter;
import de.tum.icuproject.model.Player;
import de.tum.icuproject.model.Session;
import de.tum.icuproject.persistence.PlayerRepository;
import de.tum.icuproject.persistence.couchdb.PlayerRepositoryImpl;

/**
 * The AddPlayerFragment provides fields to enter player data and stores the
 * player to the database.
 * 
 */
public class AddPlayerFragment extends Fragment implements Subscriber {

	// Used exclusively to cache the inserted information between id generation
	// and actual insertion.
	// Do not confuse it with currentPlayer of MainActivity.
	private Player currentlyInsertingPlayer;

	private SectionsPagerAdapter sectionsPagerAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_addplayer,
				container, false);

		Button btnStorePlayer = (Button) rootView.findViewById(R.id.btnAddUser);
		btnStorePlayer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				storePlayer(v);
			}
		});

		Button btnReturn = (Button) rootView
				.findViewById(R.id.btnAddUserReturn);
		btnReturn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				returnToPlayerFragment();
			}
		});

		return rootView;
	}

	/**
	 * Get the player data from the layout and stores it to the database.
	 * 
	 * @param view
	 */
	public void storePlayer(View view) {

		EditText editTextName = (EditText) getView().findViewById(
				R.id.editTextAddFirstName);
		String enteredName = editTextName.getText().toString();
		EditText editTextLastName = (EditText) getView().findViewById(
				R.id.editTextAddLastName);
		String enteredLastName = editTextLastName.getText().toString();
		EditText editTextBirthday = (EditText) getView().findViewById(
				R.id.editTextAddBirthday);
		String enteredBirthDate = editTextBirthday.getText().toString();
		EditText editTextHeight = (EditText) getView().findViewById(
				R.id.editTextAddHeight);
		String enteredHeight = editTextHeight.getText().toString();
		EditText editTextWeight = (EditText) getView().findViewById(
				R.id.editTextAddWeight);
		String enteredWeight = editTextWeight.getText().toString();

		RadioGroup radioGroupSex = (RadioGroup) getView().findViewById(
				R.id.radioGroupAddSex);
		int checkedRadioBtnId = radioGroupSex.getCheckedRadioButtonId();
		RadioButton checkedRadioBtn = (RadioButton) getView().findViewById(
				checkedRadioBtnId);
		String radioBtnValue = checkedRadioBtn.getText().toString();
		boolean isMale = true;
		if (radioBtnValue.equals(this.getString(R.string.sex_female))) {
			isMale = false;
		}

		if (!enteredName.equals("") && !enteredLastName.equals("")
				&& !enteredBirthDate.equals("") && !enteredHeight.equals("")
				&& !enteredWeight.equals("")) {
			try {
				int playerHeight = Integer.parseInt(enteredHeight);
				int playerWeight = Integer.parseInt(enteredWeight);
				this.currentlyInsertingPlayer = new Player(null, enteredName,
						enteredLastName, enteredBirthDate, playerHeight,
						playerWeight, isMale);
				PlayerRepository playerRepo = new PlayerRepositoryImpl(this);
				playerRepo.generatePlayerId();
				Toast.makeText(getView().getContext(), "Please wait...",
						Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				Toast.makeText(getView().getContext(),
						"The input is of a wrong format. Please check again!",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getView().getContext(), "No field can be empty!",
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void setCurrentPlayer(Player player) {
	}

	/**
	 * Sets the player ID.
	 * 
	 * @param view
	 */
	@Override
	public void setPlayerId(int playerId) {
		Log.d("PLAYER_ID", String.valueOf(playerId));
		Toast.makeText(getView().getContext(),
				"Generated playerId: " + playerId, Toast.LENGTH_SHORT).show();
		this.currentlyInsertingPlayer.setPlayerId(playerId);
		PlayerRepository playerRepo = new PlayerRepositoryImpl(this);
		playerRepo.insert(this.currentlyInsertingPlayer);
	}

	/**
	 * Confirms the insertion of the player and cleans the input fields.
	 * 
	 * @param view
	 */
	@Override
	public void confirmInsertion(boolean confirm) {
		Log.d("CONFIRM_INSERTION", String.valueOf(confirm));
		if (confirm) {
			Toast.makeText(getView().getContext(),
					"Inserted player? = " + confirm, Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(getView().getContext(), "Error, please try again.",
					Toast.LENGTH_SHORT).show();
		}
		// Free memory:
		this.currentlyInsertingPlayer = null;
		// Reset input fields:
		EditText editTextName = (EditText) getView().findViewById(
				R.id.editTextAddFirstName);
		editTextName.setText("");
		EditText editTextLastName = (EditText) getView().findViewById(
				R.id.editTextAddLastName);
		editTextLastName.setText("");
		EditText editTextBirthday = (EditText) getView().findViewById(
				R.id.editTextAddBirthday);
		editTextBirthday.setText("");
		EditText editTextHeight = (EditText) getView().findViewById(
				R.id.editTextAddHeight);
		editTextHeight.setText("");
		EditText editTextWeight = (EditText) getView().findViewById(
				R.id.editTextAddWeight);
		editTextWeight.setText("");
		RadioGroup radioGroupSex = (RadioGroup) getView().findViewById(
				R.id.radioGroupAddSex);
		radioGroupSex.check(R.id.radioAddSex_Female);
	}

	@Override
	public void confirmUpdate(boolean confirm) {
	}

	@Override
	public void confirmDeletion(boolean confirm) {
	}

	@Override
	public void setSessionId(int sessionId) {
	}

	/**
	 * Returns to the PlayerFragment.
	 */
	public void returnToPlayerFragment() {
		PlayerFragment playerFragment = new PlayerFragment();
		playerFragment.setSectionsPagerAdapter(sectionsPagerAdapter);
		sectionsPagerAdapter.updatePlayerFragment(playerFragment);
	}

	public void setSectionsPagerAdapter(
			SectionsPagerAdapter sectionsPagerAdapter) {
		this.sectionsPagerAdapter = sectionsPagerAdapter;
	}

	@Override
	public void setCurrentSession(Session session) {
	}

	@Override
	public Player getCurrentPlayer() {
		MainActivity mainActivity = (MainActivity) getActivity();
		return mainActivity.getCurrentPlayer();
	}

}